/**
 * 弹窗管理器
 */
class ModalManager {
    constructor() {
        this.init();
    }

    init() {
        // 使用事件委托处理文件路径链接点击事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('file-path-link') || e.target.closest('.file-path-link')) {
                e.preventDefault();
                this.handleFilePathClick(e);
            }
        });
    }

    handleFilePathClick(e) {
        const link = e.target.classList.contains('file-path-link') ? e.target : e.target.closest('.file-path-link');
        const filePath = link.getAttribute('data-file-path');
        const chunkId = link.getAttribute('data-chunk-id');
        const startPos = parseInt(link.getAttribute('data-start-pos'));
        const endPos = parseInt(link.getAttribute('data-end-pos'));
        const startLine = parseInt(link.getAttribute('data-start-line'));
        const endLine = parseInt(link.getAttribute('data-end-line'));
        
        if (filePath) {
            this.showFileContentModal(filePath, chunkId, startPos, endPos, startLine, endLine);
        }
    }

    async showFileContentModal(filePath, chunkId, startPos, endPos, startLine, endLine) {
        // 检查文件路径是否有效
        if (!filePath || typeof filePath !== 'string' || filePath.trim() === '') {
            console.error('Invalid file path:', filePath);
            alert('无效的文件路径');
            return;
        }
        
        // 清理文件路径，但不要进行编码，因为apiClient.getFileContent会处理编码
        const cleanPath = filePath.trim();
        
        // 创建弹窗
        const modal = this.createModal(cleanPath);
        document.body.appendChild(modal);
        
        // 添加事件监听器
        this.addModalEventListeners(modal);
        
        try {
            // 获取文件内容
            const response = await window.apiClient.getFileContent(cleanPath);
            
            if (response && response.content) {
                this.displayFileContent(modal, response.content, startPos, endPos, startLine, endLine);
            } else {
                this.displayError(modal, `加载文件内容失败: ${response ? (response.message || '未知错误') : '未知错误'}`);
            }
        } catch (error) {
            console.error('Error loading file content:', error);
            this.displayError(modal, `加载文件内容失败: ${error.message || '请检查服务器连接'}`);
        }
    }

    createModal(filePath) {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                    <h3 class="text-lg font-semibold text-gray-800">文件内容: ${filePath}</h3>
                    <button class="text-gray-500 hover:text-gray-700 close-modal">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-6 overflow-auto max-h-[calc(80vh-120px)]">
                    <div class="text-center py-8">
                        <i class="fas fa-spinner fa-spin text-2xl text-blue-500 mb-2"></i>
                        <p class="text-gray-600">正在加载文件内容...</p>
                    </div>
                </div>
            </div>
        `;
        return modal;
    }

    addModalEventListeners(modal) {
        // 添加关闭弹窗事件
        modal.querySelector('.close-modal').addEventListener('click', () => {
            this.closeModal(modal);
        });
        
        // 点击背景关闭弹窗
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeModal(modal);
            }
        });
    }

    closeModal(modal) {
        if (modal && modal.parentNode) {
            document.body.removeChild(modal);
        }
    }

    displayFileContent(modal, fileContent, startPos, endPos, startLine, endLine) {
        // 将文件内容按行分割
        const lines = fileContent.split('\n');
        
        // 使用传入的行号信息
        const actualStartLine = startLine || 1;
        const actualEndLine = endLine || lines.length;
        
        // 生成带行号的HTML内容
        const contentHtml = this.generateLineNumberedContent(lines, startLine, endLine);
        
        // 更新弹窗内容
        const contentContainer = modal.querySelector('.p-6');
        contentContainer.innerHTML = `
            <div class="mb-4 text-sm text-gray-600">
                匹配位置: 第 ${actualStartLine}-${actualEndLine} 行 (字符位置: ${startPos}-${endPos})
            </div>
            <div class="border border-gray-200 rounded-lg overflow-hidden font-mono text-sm">
                ${contentHtml}
            </div>
        `;
        
        // 滚动到匹配位置
        this.scrollToHighlightedContent(contentContainer);
    }

    generateLineNumberedContent(lines, startLine, endLine) {
        let contentHtml = '';
        for (let i = 0; i < lines.length; i++) {
            const lineNumber = i + 1;
            const isHighlighted = lineNumber >= startLine && lineNumber <= endLine;
            
            contentHtml += `
                <div class="flex ${isHighlighted ? 'bg-yellow-100' : ''}">
                    <div class="w-12 text-right pr-3 text-gray-500 select-none border-r border-gray-200">
                        ${lineNumber}
                    </div>
                    <div class="flex-1 pl-3 text-gray-700 ${isHighlighted ? 'font-medium' : ''}">
                        ${this.escapeHtml(lines[i])}
                    </div>
                </div>
            `;
        }
        return contentHtml;
    }

    scrollToHighlightedContent(contentContainer) {
        setTimeout(() => {
            const highlightedElements = contentContainer.querySelectorAll('.bg-yellow-100');
            if (highlightedElements.length > 0) {
                highlightedElements[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }, 100);
    }

    displayError(modal, errorMessage) {
        const contentContainer = modal.querySelector('.p-6');
        contentContainer.innerHTML = `
            <div class="text-center py-8 text-red-500">
                <i class="fas fa-exclamation-circle text-2xl mb-2"></i>
                <p>${errorMessage}</p>
            </div>
        `;
    }

    escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
}

// 创建全局弹窗管理器实例
window.modalManager = new ModalManager();